#!/usr/bin/env bash
set -euo pipefail

# 自动部署脚本: 将当前目录部署到 /opt/mcp-thingsboard 并注册为 systemd 服务。
# 用法 (需 root 权限):
#   sudo ./deploy_service.sh --jwt "Bearer ..."
# 可选参数:
#   --jwt <TOKEN>        指定 ThingsBoard JWT (可带 "Bearer " 前缀)
#   --service-user <U>   指定运行服务的系统用户 (默认 root)
#   --no-start           不立即启动服务
#   --no-enable          仅部署不设置开机自启
#   --skip-pip           跳过依赖安装 (假设 .venv 已准备好)

TARGET_DIR="/opt/mcp-thingsboard"
SERVICE_FILE="/etc/systemd/system/mcp-thingsboard.service"
SERVICE_NAME="mcp-thingsboard.service"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
JWT_VALUE=""
SERVICE_USER="root"
SERVICE_GROUP="root"
AUTO_START=1
AUTO_ENABLE=1
SKIP_PIP=0

usage() {
  sed -n '2,16p' "$0"
  exit 0
}

if [[ $EUID -ne 0 ]]; then
  echo "[!] 请使用 root 权限运行 (例如 sudo ./deploy_service.sh)" >&2
  exit 1
fi

while [[ $# -gt 0 ]]; do
  case "$1" in
    --jwt)
      shift || { echo "[!] --jwt 需要参数" >&2; exit 1; }
      JWT_VALUE="${1:-}"
      ;;
    --service-user)
      shift || { echo "[!] --service-user 需要参数" >&2; exit 1; }
      SERVICE_USER="${1:-}"
      SERVICE_GROUP="$SERVICE_USER"
      ;;
    --no-start)
      AUTO_START=0
      ;;
    --no-enable)
      AUTO_ENABLE=0
      ;;
    --skip-pip)
      SKIP_PIP=1
      ;;
    --help|-h)
      usage
      ;;
    *)
      echo "[!] 未知参数: $1" >&2
      usage
      ;;
  esac
  shift || break
done

if ! id "$SERVICE_USER" >/dev/null 2>&1; then
  echo "[!] 系统用户 $SERVICE_USER 不存在" >&2
  exit 1
fi

SERVICE_GROUP="$(id -gn "$SERVICE_USER")"

SYS_PYTHON="$(command -v python3)"
if [[ -z "$SYS_PYTHON" ]]; then
  echo "[!] 未找到 python3，请先安装" >&2
  exit 1
fi

mkdir -p "$TARGET_DIR"

# 复制项目文件到 /opt，保留 .env/.venv，排除 git 目录等
rsync -a --delete \
  --exclude '.git' \
  --exclude '.venv' \
  --exclude '.env' \
  --exclude '__pycache__' \
  --exclude 'server.log' \
  --exclude 'deploy_service.sh' \
  --exclude 'run.sh~' \
  --exclude '.python-version' \
  "$SCRIPT_DIR/" "$TARGET_DIR/"

# 保留部署脚本自身供后续更新
install -m 755 "$SCRIPT_DIR/deploy_service.sh" "$TARGET_DIR/deploy_service.sh"

# 保持现有 .env，不再自动写入 JWT。请手动编辑 /opt/mcp-thingsboard/.env。

if [[ $SKIP_PIP -eq 0 ]]; then
  if [[ ! -d "$TARGET_DIR/.venv" ]]; then
    echo "[*] 创建虚拟环境 $TARGET_DIR/.venv" >&2
    "$SYS_PYTHON" -m venv "$TARGET_DIR/.venv"
  fi
  echo "[*] 安装依赖" >&2
  "$TARGET_DIR/.venv/bin/pip" install --upgrade pip >/dev/null
  "$TARGET_DIR/.venv/bin/pip" install -r "$TARGET_DIR/requirements.txt" >/dev/null
else
  echo "[*] 跳过依赖安装 (--skip-pip)" >&2
fi

chown -R "$SERVICE_USER:$SERVICE_GROUP" "$TARGET_DIR"
chmod +x "$TARGET_DIR/run.sh"

cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=MCP ThingsBoard Service
After=network.target

[Service]
Type=simple
User=$SERVICE_USER
Group=$SERVICE_GROUP
WorkingDirectory=$TARGET_DIR
Environment=PYTHONUNBUFFERED=1
Environment=SKIP_PIP_INSTALL=1
ExecStart=$TARGET_DIR/run.sh http
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

chmod 644 "$SERVICE_FILE"

systemctl daemon-reload

if [[ $AUTO_ENABLE -eq 1 ]]; then
  systemctl enable "$SERVICE_NAME"
fi

if [[ $AUTO_START -eq 1 ]]; then
  systemctl restart "$SERVICE_NAME"
  systemctl --no-pager status "$SERVICE_NAME" || true
else
  echo "[*] 已创建服务文件，可通过 \"systemctl start $SERVICE_NAME\" 手动启动" >&2
fi

cat <<EOM
部署完成。
- 代码目录: $TARGET_DIR
- 服务文件: $SERVICE_FILE
- 运行用户: $SERVICE_USER
- systemd 服务名: $SERVICE_NAME
EOM
